<template>
  <div class="sr-container" ref="srRef" v-scroll="onScroll">
    <van-pull-refresh v-model="isLoading" success-text="刷新成功" @refresh="onRefresh">
      <div ref="srmainRef">
        <slot></slot>
      </div>
    </van-pull-refresh>
    <div class="loadmore" v-if="isLoadmore">
      <van-loading size="1rem">加载中...</van-loading>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { vScroll } from '@vueuse/components'
import { useElementBounding } from '@vueuse/core'

const emits = defineEmits(['refresh', 'loadmore'])

const srRef = ref()
const srmainRef = ref()
const isLoading = ref(false)
const isLoadmore = ref(false);

function onScroll(e) {
  const { height: srHeight } = useElementBounding(srRef)
  const { height: srmainHeight } = useElementBounding(srmainRef)
  if (e.y.value >= srmainHeight.value - srHeight.value - 20) {
    isLoadmore.value = true
  } else {
    isLoadmore.value = false
  }
  // console.log('滚动距离顶部高度', e.y.value, '阈值', srmainHeight.value - srHeight.value - 40, '加载更多', isLoadmore.value)
}

function onRefresh() {
  isLoading.value = true;
  // console.log('下拉刷新');
  emits('refresh', (flag) => {
    // 通过回调来关闭下拉刷新
    isLoading.value = flag
  })
}

// 监听 懒加载
watch(isLoadmore, (newVal) => {
  if (newVal) {
    // console.log('上拉加载');
    emits('loadmore')
  }
})

</script>

<style lang="scss" scoped>
.sr-container {
  width: 100%;
  height: 100%;
  overflow: auto;

  .loadmore {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 2rem;
  }
}
</style>